//
//  WJPurchaseViewController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/10/15.
//

import UIKit
import SnapKit
import StoreKit
import Lottie

protocol WJPurchaseViewControllerProtocol {
    var dimissAction: (() -> Void)? { get set }
}

class WJPurchaseViewController: UIViewController, WJPurchaseViewControllerProtocol {
    
    var products: [SKProduct] = [] {
        didSet {
            setDisplayProducts()
        }
    }
    
    var displayProducts: [SKProduct] = [] {
        didSet {
            updatePlanViews()
        }
    }
    
    var dimissAction:(() -> Void)?
    private var showDiscount: Bool = true
    
    // 存储当前选中的套餐视图
    private var selectedPlanView: SMPlanView?
    private var planViews: [SMPlanView] = []
    private var freeProduct: SKProduct? = nil

    // MARK: - 添加 ScrollView 相关组件
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.showsVerticalScrollIndicator = false
        scrollView.alwaysBounceVertical = true
        scrollView.backgroundColor = .clear
        return scrollView
    }()
    
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()

    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
        setupNavigationBar()
        setupConstraints()
        loadProducts()
        WJPurchaseManager.shared.delegate = self
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        // 视图消失时停止播放以节省资源
        animationView.stop()
    }

    private func validateOfferEligibility() {
        WJUserManager.shared.shouldShowOffer {  [weak self] show in
            WJProgressHUD.dismiss()
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.showDiscount = show
            }
        }
    }
    
    func loadProducts() {
        let identifiers: Set<String> = Set(WJSku.allCases.map { $0.rawValue })
        WJPurchaseManager.shared.fetchProducts(identifiers: identifiers)
    }
    
    func setDisplayProducts() {
        let trialSwitchIsOn = trialSwitch.isOn
        let productIds: [String]
        if trialSwitchIsOn {
            productIds = RemoteConfigValues.firstAndThirdSkus
        } else {
            productIds = RemoteConfigValues.firstTwoSkus
        }

       for product in products {
           if product.productIdentifier == WJSku.weeklyFree.rawValue {
               freeProduct = product
           }
       }
        
        self.displayProducts = productIds
            .compactMap { productId in
                products.first { $0.productIdentifier == productId }
            }
    }
    
    // MARK: - 设置基础 UI
    private func setupView() {
        view.backgroundColor = UIColor(hex: "#061B31")
        
        // 添加 ScrollView 和 ContentView
        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        
        // 将所有内容添加到 contentView 中
        [animationView, titleLabel, switchBgView, plansStackView].forEach {
            contentView.addSubview($0)
        }
        
        view.addSubview(tryForFreeButton)
        view.addSubview(hStackView)
        
        [trialSwitch, trialLabel, trialDescriptionLabel].forEach {
            switchBgView.addSubview($0)
        }
    }
    
    // MARK: - SnapKit 约束布局
    private func setupConstraints() {
        // ScrollView 约束
        scrollView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.bottom.equalTo(tryForFreeButton.snp.top).offset(-10)
        }
        
        // ContentView 约束
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(scrollView)
            make.bottom.equalTo(plansStackView.snp.bottom).offset(20)
        }
        
        // 动画视图
        animationView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalTo(titleLabel.snp.top).offset(-10)
        }
        
        // 标题
        titleLabel.snp.makeConstraints { make in
            make.bottom.equalTo(switchBgView.snp.top).offset(-24)
            make.centerX.equalToSuperview()
            make.height.equalTo(30)
        }
        
        // 开关背景视图
        switchBgView.snp.makeConstraints { make in
            make.bottom.equalTo(plansStackView.snp.top).offset(-12)
            make.leading.trailing.equalToSuperview().inset(14)
            make.height.equalTo(60)
        }
        
        // 试用开关
        trialSwitch.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-16)
        }
        
        // 试用标签
        trialLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.trailing.equalTo(trialSwitch.snp.leading).offset(-10)
            make.top.equalToSuperview().offset(8)
        }
        
        // 试用说明
        trialDescriptionLabel.snp.makeConstraints { make in
            make.leading.trailing.equalTo(trialLabel)
            make.bottom.equalToSuperview().offset(-8)
        }
        
        // 套餐堆栈视图
        plansStackView.snp.makeConstraints { make in
            make.bottom.equalTo(tryForFreeButton.snp.top).offset(-32)
            make.leading.trailing.equalToSuperview().inset(14)
            make.height.equalTo(calculatePlansStackViewHeight())
        }
        
        // 免费试用按钮
        tryForFreeButton.snp.makeConstraints { make in
            make.bottom.equalTo(hStackView.snp.top).offset(-15)
            make.leading.trailing.equalToSuperview().inset(32)
            make.height.equalTo(64)
        }
        
        // 底部链接堆栈
        hStackView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.height.equalTo(15)
            make.bottom.equalToSuperview().offset(-safeAreaBottom - 5)
        }
    }
    
    @objc func changeSwitchState(_ button: UISwitch) {
        if button.isOn {
            trialLabel.text = "Free trial enabled"
        } else {
            trialLabel.text = "Enable free trial"
        }
        setDisplayProducts()
        updateContinueButton()
    }
    
    // MARK: - 动态更新套餐视图
    private func updatePlanViews() {
        // 清空现有视图
        planViews.forEach { $0.removeFromSuperview() }
        planViews.removeAll()
        selectedPlanView = nil
        

        // 根据产品创建新的套餐视图
        for (index, product) in displayProducts.enumerated() {
            let planView = createPlanView(for: product, index: index)
            planViews.append(planView)
            plansStackView.addArrangedSubview(planView)
        }
        
        // 更新套餐堆栈视图的高度约束
        plansStackView.snp.updateConstraints { make in
            make.height.equalTo(calculatePlansStackViewHeight())
        }
        
        // 默认选中第一个套餐
        if trialSwitch.isOn {
            if let lastPlanView = planViews.last {
                selectPlan(view: lastPlanView)
            }
        } else {
            if let firstPlanView = planViews.first {
                selectPlan(view: firstPlanView)
            }
        }
        
        // 强制布局更新，确保 ScrollView 内容尺寸正确
        view.layoutIfNeeded()
    }
    
    func updateContinueButton() {
        
        if let selectProduct = getSelectedProduct() {
            if selectProduct.productIdentifier == WJSku.weeklyFree.rawValue {
                tryForFreeButton.setTitle("Try for Free", for: .normal)
            } else {
                tryForFreeButton.setTitle("Continue", for: .normal)
            }
        } else {
            tryForFreeButton.setTitle("Try for Free", for: .normal)
        }
    }
    
    // MARK: - 创建套餐视图
    private func createPlanView(for product: SKProduct, index: Int) -> SMPlanView {
        // 根据产品信息生成显示内容
        let title = getDisplayTitle(for: product)
        let price = getDisplayPrice(for: product, showFree: true)
        let subPrice = getDisplaySubPrice(for: product)
        let isPopular = determineIfPopular(for: product, index: index)
        
        let planView = SMPlanView(
            title: title,
            price: price,
            subPrice: subPrice,
            isPopular: isPopular
        )
        
        planView.tapHandler = { [weak self] in
            self?.selectPlan(view: planView)
        }
        
        return planView
    }
    
    // MARK: - 产品信息格式化
    private func getDisplayTitle(for product: SKProduct) -> String {
        // 根据产品ID或本地化标题判断类型
        let productId = product.productIdentifier.lowercased()
        
        if productId.contains("yearly") || productId.contains("annual") {
            return "Yearly"
        } else if productId.contains("monthly") || productId.contains("month") {
            return "Monthly"
        } else if productId.contains("weekly") || productId.contains("week") {
            return "Weekly"
        } else {
            return product.localizedTitle
        }
    }
    
    private func getDisplayPrice(for product: SKProduct, showFree: Bool = false) -> String {
        // 使用 NumberFormatter 格式化价格
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .currency
        numberFormatter.locale = product.priceLocale

        if showFree, showDiscount {
            if product.productIdentifier.lowercased() == WJSku.weeklyFree.rawValue {
                if let freeDays = WJUserManager.shared.getIntroductoryPriceDurationInDays(product: product) {
                    return "Free for \(freeDays) days"
                } else {
                    return "Free for 3 days"
                }
            }
        }
        
        if let formattedPrice = numberFormatter.string(from: product.price) {
            // 根据订阅周期添加后缀
            let productId = product.productIdentifier.lowercased()
            if productId.contains("yearly") || productId.contains("annual") {
                return "\(formattedPrice)/year"
            } else if productId.contains("monthly") || productId.contains("month") {
                return "\(formattedPrice)/month"
            } else if productId.contains("weekly") || productId.contains("week") {
                return "\(formattedPrice)/week"
            }
            return formattedPrice
        }
        
        return "\(product.price) \(product.priceLocale.currencySymbol ?? "")"
    }
    
    private func getDisplaySubPrice(for product: SKProduct) -> String {
        // 计算并显示等效的每周价格或其他比较价格
        let productId = product.productIdentifier.lowercased()
        let price = product.price.doubleValue
        
        if productId.contains("yearly") || productId.contains("annual") {
            let weeklyPrice = price / 52.0
            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .currency
            numberFormatter.locale = product.priceLocale
            if let formattedWeeklyPrice = numberFormatter.string(from: NSNumber(value: weeklyPrice)) {
                return "just \(formattedWeeklyPrice)/week"
            }
        } else if productId.contains("weekly") || productId.contains("week") {
            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .currency
            numberFormatter.locale = product.priceLocale
            
            if productId == WJSku.weeklyFree.rawValue, showDiscount {
                
                if let formattedPrice = numberFormatter.string(from: product.price) {
                    // 根据订阅周期添加后缀
                    return "then \(formattedPrice)/week"
                }
            } else if productId == WJSku.weeklyDiscount.rawValue, showDiscount {
                
                if let formattedPrice = numberFormatter.string(from: product.price) {
                    // 根据订阅周期添加后缀
                    return "1 week \(formattedPrice)"
                }
                
            } else {
                let dayPrice = price / 7.0
                if let formattedDayPrice = numberFormatter.string(from: NSNumber(value: dayPrice)) {
                    return "just \(formattedDayPrice)/day"
                }
            }
        }
        
        return ""
    }
    
    private func determineIfPopular(for product: SKProduct, index: Int) -> Bool {
        // 根据业务逻辑判断哪个套餐最受欢迎
        // 这里可以根据价格、产品类型等判断
        let productId = product.productIdentifier.lowercased()
        return productId.contains("yearly") || productId.contains("annual")
    }
    
    // MARK: - 设置导航栏
    private func setupNavigationBar() {
        // 左侧关闭按钮
        let leftBar = UIBarButtonItem(
            image: UIImage(named: "Icon_line_close")?.withRenderingMode(.alwaysTemplate),
            style: .plain,
            target: self,
            action: #selector(clickLeftBarItemAction(_:))
        )
        leftBar.tintColor = .white
        navigationItem.leftBarButtonItem = leftBar
        
        // 右侧 "Restore" 按钮
        let rightBtn = UIButton(type: .custom)
        rightBtn.setTitle("Restore", for: .normal)
        rightBtn.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        rightBtn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        rightBtn.layer.cornerRadius = 16
        rightBtn.layer.borderColor = UIColor(hex: "#FFFFFF").withAlphaComponent(0.6).cgColor
        rightBtn.layer.borderWidth = 1
        rightBtn.addTarget(self, action: #selector(restoreButtonTapped(_:)), for: .touchUpInside)
        rightBtn.frame = CGRect(x: 0, y: 0, width: 60, height: 32)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
    }
    
    private lazy var animationView: LottieAnimationView = {
        let animationView = LottieAnimationView(name: "animation1")
        animationView.contentMode = .scaleAspectFit
        animationView.loopMode = .loop
        animationView.animationSpeed = 1.0
        animationView.play()
        return animationView
    }()
    
    // MARK: - 懒加载 UI 组件
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "Unlock all features"
        label.textColor = UIColor(hex: "#FFFFFF")
        label.font = UIFont.systemFont(ofSize: 32, weight: .semibold)
        return label
    }()
    
    private lazy var trialSwitch: UISwitch = {
        let switchView = UISwitch()
        switchView.isOn = false
        switchView.onTintColor = UIColor.systemBlue
        switchView.tintColor = UIColor(hex: "#BFBFBF")
        switchView.backgroundColor = UIColor(hex: "#BFBFBF")
        switchView.layer.cornerRadius = switchView.frame.height / 2
        switchView.clipsToBounds = true
        switchView.addTarget(self, action: #selector(changeSwitchState(_:)), for: .valueChanged)
        return switchView
    }()
    
    private lazy var trialLabel: UILabel = {
        let label = UILabel()
        label.text = "Enable free trial"
        label.textColor = UIColor(hex: "#FFFFFF")
        label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        return label
    }()
    
    private lazy var trialDescriptionLabel: UILabel = {
        let label = UILabel()
        label.text = "You will receive a due notice"
        label.textColor = UIColor(hex: "#FFFFFF", alpha: 0.6)
        label.font = UIFont.systemFont(ofSize: 16)
        return label
    }()
    
    private lazy var switchBgView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        view.layer.masksToBounds = true
        view.layer.cornerRadius = 30
        view.layer.borderWidth = 1.0
        view.layer.borderColor = UIColor(hex: "#FFFFFF", alpha: 0.16).cgColor
        return view
    }()
    
    // 动态套餐视图容器
    private lazy var plansStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 16
        stackView.distribution = .fillEqually
        return stackView
    }()
    
    private lazy var tryForFreeButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Try for Free", for: .normal)
        button.backgroundColor = UIColor(hex: "#1F87F6")
        if let backgroundImage = UIImage(named: "button_layer") {
            let capInsets = UIEdgeInsets(top: 0, left: 32, bottom: 0, right: 32)
            let resizableImage = backgroundImage.resizableImage(withCapInsets: capInsets, resizingMode: .stretch)
            button.setBackgroundImage(resizableImage, for: .normal)
        }
        button.setTitleColor(UIColor(hex: "#FFFFFF"), for: .normal)
        button.titleLabel?.font = UIFont.montserratMedium(20)
        button.layer.cornerRadius = 32
        button.clipsToBounds = true
        button.addTarget(self, action: #selector(tryForFreeTapped), for: .touchUpInside)
        return button
    }()

    private lazy var privacyLabel: UILabel = {
        let label = UILabel()
        label.text = "Privacy"
        label.textColor = UIColor(hex: "#FFFFFF").withAlphaComponent(0.7)
        label.font = UIFont.systemFont(ofSize: 10)
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(privacyTapped)))
        return label
    }()
    
    private lazy var termsLabel: UILabel = {
        let label = UILabel()
        label.text = "Terms"
        label.textColor = UIColor(hex: "#FFFFFF").withAlphaComponent(0.7)
        label.font = UIFont.systemFont(ofSize: 10)
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(termsTapped)))
        return label
    }()
    
    private lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: "#FFFFFF").withAlphaComponent(0.7)
        return view
    }()

    lazy var hStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .fill
        stackView.alignment = .center
        stackView.spacing = 12.0
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        stackView.addArrangedSubview(privacyLabel)
        stackView.addArrangedSubview(lineView)
        stackView.addArrangedSubview(termsLabel)
        
        // 使用 SnapKit 设置 lineView 尺寸
        lineView.snp.makeConstraints { make in
            make.width.equalTo(2.0 / UIScreen.main.scale) // 物理像素2px
            make.height.equalTo(12) // 合适的高度
        }
        
        return stackView
    }()
    
    private func calculatePlansStackViewHeight() -> CGFloat {
        let planHeight: CGFloat = 60
        let spacing: CGFloat = 12
        return CGFloat(displayProducts.count) * planHeight + CGFloat(displayProducts.count - 1) * spacing
    }
    
    // MARK: - 套餐选中逻辑
    private func selectPlan(view: SMPlanView) {
        // 重置所有套餐的选中状态
        planViews.forEach { $0.resetSelection() }
        // 设置当前选中状态
        view.setSelected(true)
        selectedPlanView = view
        updateContinueButton()
    }
    
    // MARK: - 获取当前选中的产品
    private func getSelectedProduct() -> SKProduct? {
        guard let selectedPlanView = selectedPlanView,
              let selectedIndex = planViews.firstIndex(of: selectedPlanView) else {
            return nil
        }
        return displayProducts[selectedIndex]
    }
    
    // MARK: - 按钮/手势事件
    @objc func clickLeftBarItemAction(_ item: UIBarButtonItem) {
        dismiss(animated: true) { [weak self] in
            guard let self = self else { return }
            dimissAction?()
        }
    }
    
    @objc func restoreButtonTapped(_ button: UIButton) {
        WJProgressHUD.showLoading()
        WJPurchaseManager.shared.restorePurchases()
    }
    
    @objc func tryForFreeTapped() {
        WJProgressHUD.showLoading()
        guard let selectedProduct = getSelectedProduct() else {
            if let freeProduct = self.freeProduct {
                WJPurchaseManager.shared.purchaseProduct(freeProduct)
            }
            return
        }
        WJPurchaseManager.shared.purchaseProduct(selectedProduct)
    }
    
    @objc func privacyTapped() {
        // 隐私政策跳转
        if let url = URL(string: "https://www.freeprivacypolicy.com/live/b4baff6e-61f8-491e-b138-b13696060fd3") {
            UIApplication.shared.open(url)
        }
    }
    
    @objc func termsTapped() {
        // 条款跳转
        if let url = URL(string: "https://www.freeprivacypolicy.com/live/f2a037ca-a61e-4802-a0b5-8e5785c44762") {
            UIApplication.shared.open(url)
        }
    }
}

extension WJPurchaseViewController: WJPurchaseManagerDelegate {
    func productsLoaded(products: [SKProduct]) {
        self.products = products
        validateOfferEligibility()
    }
    
    func purchaseCompleted(result: WJPurchaseResult) {
        switch result {
        case .success(_):
            WJProgressHUD.showInfo(with: "Purchase successful")
           dismiss(animated: true)
            
        case .failure(let error):
            WJProgressHUD.showInfo(with: error)
            
        case .cancelled:
            WJProgressHUD.showInfo(with: "Purchase Canceled")
        case .restored:
            WJProgressHUD.showInfo(with: "Restore successful")
        case .restoreFailure(let error):
            WJProgressHUD.showInfo(with: error)
        }
    }
    
    func productsRequestFailed(error: String) {
        WJProgressHUD.showInfo(with: error)
    }
}
